﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace InstrumentationLibrary.Config
{
    /// <summary>
    /// Aspect details
    /// </summary>
    public class AspectElement : ConfigurationElement
    {
        private const string nameAttribute = "name";
        private const string aspectTypeAttribute = "aspectType";

        /// <summary>
        /// Aspect name, used to identify the aspect.
        /// </summary>
        [ConfigurationProperty(nameAttribute, IsRequired = true)]
        public string Name
        {
            get
            {
                return this[nameAttribute] as string;
            }
            set
            {
                this[nameAttribute] = value;
            }
        }

        /// <summary>
        /// Aspect type name, required to create an instance of the aspect.
        /// </summary>
        [ConfigurationProperty(aspectTypeAttribute, IsRequired = true)]
        public string AspectType
        {
            get
            {
                return this[aspectTypeAttribute] as string;
            }
            set
            {
                this[aspectTypeAttribute] = value;
            }
        }

        /// <summary>
        /// Create an instance of the aspect.
        /// </summary>
        /// <returns></returns>
        public IInstrumentationAspect CreateAspect()
        {
            var type = Type.GetType(AspectType);

            var aspect = Activator.CreateInstance(type) as IInstrumentationAspect;

            if (aspect == null)
            {
                throw new ConfigurationErrorsException(
                    string.Format("Aspect {0} does not implement the required interface {1}",
                                    AspectType,
                                    typeof(IInstrumentationAspect).FullName));
            }

            return aspect;
        }
    }
}
